<template>
  <el-dialog v-model="props.addBtn" width="500"
             :before-close="off"
             :center="true">
      <el-upload
          class="upload-demo"
          drag
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          multiple
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖放到此处或 <em>点击选择文件</em>
        </div>
      </el-upload>
      
      <!-- 显示已选择的文件列表 -->
      <div v-if="fileList.length > 0" style="margin-top: 16px;">
        <h4>已选择的文件：</h4>
        <div v-for="(file, index) in fileList" :key="index" style="margin: 8px 0; padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px;">
          <span>{{ file.name }}</span>
          <el-button type="danger" size="small" style="float: right;" @click="removeFile(index)">删除</el-button>
        </div>
      </div>
      
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="off">取消</el-button>
        <el-button type="primary" @click="Add" :loading="uploading">
          {{ uploading ? '上传中...' : '确认上传' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { UploadFilled } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload } from '@/service/oss.ts';

const props = defineProps({
  addBtn: Boolean
});
const emit = defineEmits(['update-status', 'upload-success']);

// 文件列表
const fileList = ref<any[]>([])
// 上传状态
const uploading = ref(false)

// 处理文件选择
const handleFileChange = (_file: any, files: any[]) => {
  fileList.value = files
}

// 删除文件
const removeFile = (index: number) => {
  fileList.value.splice(index, 1)
}

// 上传文件
const Add = async() => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请先选择要上传的文件')
    return
  }
  
  uploading.value = true
  
  try {
    // 创建FormData对象
    const formData = new FormData()
    // 将所有文件添加到FormData中
    fileList.value.forEach((file) => {
      formData.append('file', file.raw)
    })
    
    // 调用上传接口
    const data = await Upload(formData)
    if (data.code === 200) {
      ElMessage.success('文件上传成功')
      // 清空文件列表
      fileList.value = []
      // 通知父组件上传成功，刷新列表
      emit('upload-success')
      // 关闭对话框
      off()
    } else {
      ElMessage.error(response.data.message || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败，请重试')
  } finally {
    uploading.value = false
  }
}

const off = () => {
  // 清空文件列表
  fileList.value = []
  emit("update-status", false);
}

</script>
